package org.tlang.context;

import org.tlang.type.Type;

import java.util.Arrays;

public class TypeTable {
    private final TypeTable outer;
    private Type[] types;
    private final String tag; // for debug

    public TypeTable(int initSize, String tag) {
        this(initSize, null, tag);
    }

    public TypeTable(int initSize, TypeTable outer, String tag) {
        this.outer = outer;
        this.types = new Type[initSize];
        this.tag = tag;
    }

    public TypeTable outer() {
        return outer;
    }

    public Type get(int nest, int index) {
        if (nest == 0) {
            if (index >= types.length || index < 0) {
                return null;
            } else {
                return types[index];
            }
        } else if (outer == null) {
            return null;
        } else {
            return outer.get(nest - 1, index);
        }
    }

    /**
     * will add or update
     *
     * @param index position will be added
     * @param type  Type Object
     */
    public void put(int index, Type type) {
        if (index >= types.length) {
            int newLength = types.length << 1;
            if (index >= newLength) {
                newLength = index + 1;
            }
            types = Arrays.copyOf(types, newLength); // 扩容
        }

        types[index] = type;
    }

    @Override
    public String toString() {
        return tag;
    }
}
